package com.ruoyi.framework.web.utils;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.po.SseEmitterPo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

 /**
 * @author zxg
 * @date 2023-08-17
 * @Desc 服务端向客户端发送消息 单向
 */
@Slf4j
public class SseEmitterUtils {
    private static final Map<String, SseEmitter> SSE_EMITTER_MAP = new ConcurrentHashMap<>();

    /**
     * 添加链接
     * @param clientId id
     * @param emitter 链接内容
     */
    public static void putSseEmitter(String clientId, SseEmitter emitter){
        SSE_EMITTER_MAP.put(clientId,emitter);
    }

    /**
     * 创建链路
     * @param clientId 客户端id
     * @throws IOException 异常
     */
    public static SseEmitter createSseEmitter(String clientId) throws IOException {
        SseEmitter sseEmitter = new SseEmitter(0L);
        SSE_EMITTER_MAP.put(clientId, sseEmitter);
        sseEmitter.send(JSON.toJSONString(new SseEmitterPo<String>()));
        putSseEmitter(clientId,sseEmitter);
        return sseEmitter;
    }

    /**
     * 发送消息
     * @param clientId 客户端id
     * @param msg 消息
     */
    public static void sendMsg(String clientId,String msg) {
        try {
            SseEmitter sseEmitter = SSE_EMITTER_MAP.get(clientId);
            log.info(clientId);
            if (sseEmitter != null) {
                sseEmitter.send(msg);
            }
        } catch (IOException e) {

            log.error("IOException!", e);
        }
    }


    /**
     * 发送结构化的数据
     * @param clientId 客户端id
     * @param data 消息
     */
    public static void sendMsgInfo(String clientId, SseEmitterPo<T> data) {
        try {
            SseEmitter sseEmitter = SSE_EMITTER_MAP.get(clientId);
            log.info(clientId);
            if (sseEmitter != null) {
                sseEmitter.send(JSON.toJSONString(data));
            }
        } catch (IOException e) {

            log.error("IOException!", e);
        }
    }

    /**
     * 给所有客户端发送消息
     * @param data 消息内容
     */
    public static void sendMsgAllClient(SseEmitterPo data){
        for(String key: SSE_EMITTER_MAP.keySet()){
            sendMsgInfo(key,data);
        }
    }


    /**
     * 关闭消息链路
     * @param clientId 客户端id
     */
    public static void closeSseEmitter(String clientId){
        SseEmitter sseEmitter = SSE_EMITTER_MAP.get(clientId);
        if (sseEmitter != null) {
            SSE_EMITTER_MAP.remove(clientId);
            sseEmitter.complete();
        }
    }

     /**
      * 关闭所有
      */
     public static void closeAll(){
         for(String key: SSE_EMITTER_MAP.keySet()){
             closeSseEmitter(key);
         }
     }
}
